<?php

class SetMemoAction extends CAction
{
    public function run()
    {
        if(!isset($_GET['recipeId']) || !isset($_POST['value']) || !isset($_POST['step']))
            throw new CHttpException(400,'the request is invalid');
        
        $step=Step::loadObjectById($_POST['step'],array('memo'));
        if($step===null)
            throw new CHttpException(404,'The requested step does not exist.');
        if($step->recipeId!=$_GET['recipeId'])
            throw new CHttpException(403,'cannot edit the step not belong to the recipe');
        if($step->userId!=Yii::app()->user->id)
            throw new CHttpException(403,'cannot edit the step not belong to you');

        $recipe=Recipe::loadObjectById($_GET['recipeId'],array('steps'));
        if($recipe===null)
            throw new CHttpException(404,'The requested recipe does not exist.');
        if(array_search($_POST['step'], $recipe->steps)===false)
            throw new CHttpException(404,'The requested step does not belong to the recipe.');
            
        $succ=false;
        if($_POST['value']===$step->memo){
            $succ=true;
        }
        else {                 
            $oldMemo=$step->memo;                
            $step->memo=$_POST['value'];
            $succ=Step::saveObject($step,array('memo'));
            if(!$succ){
                $step->memo=$oldMemo;
            }
            else {
                Recipe::saveObject($recipe,array('updateTime'));
            }
        }

        $this->controller->renderPartial('/common/editInPlace',array(
            'succ'=>$succ, 
            'data'=>$step->memo,
            'error'=>$step->getError('memo'),
        ));
    }
}

?>